/*
Java source file
Copyright: Umschalt.com 2012
*/
package com.david.documentation.domain.dao.doku;

import com.david.documentation.domain.dao.AbstractDAO;
import com.david.documentation.domain.entities.category.Category;
import com.david.documentation.domain.entities.doku.Doku;
import com.david.documentation.domain.entities.tags.Tag;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import java.util.Date;
import java.util.List;

@Repository(value = "dokuDao")
public class DokuDaoImpl extends AbstractDAO<Doku> implements DokuDao {

	@PersistenceContext
    private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public Class<Doku> getClazz() {
		return Doku.class;
	}

	@Transactional
	public List<Doku> findDokusToday(int start,int count) {
        Query query = getEntityManager().createQuery("from " + getClazz().getSimpleName() + " e where e.date >= :aDate");
        query.setParameter("aDate", new Date(), TemporalType.DATE);
		if (start != 0){
			query.setFirstResult(start);
		}
		if (count != 0){
			query.setMaxResults(count);
		}
        return query.getResultList();
    }
	@Transactional
	public List<Doku> findDokusByTag(Tag tag,int start,int count) {
		Query query = getEntityManager().createNativeQuery("SELECT doku.* FROM doku,DOKU_TAGS WHERE DOKU_TAGS.DOKU_ID = doku.DOKU_ID AND DOKU_TAGS.TAG_ID = :tagId",Doku.class);
        query.setParameter("tagId", tag.getId());
		if (start != 0){
			query.setFirstResult(start);
		}
		if (count != 0){
			query.setMaxResults(count);
		}
		return (List<Doku>) query.getResultList();
	}
	@Transactional
	public List<Doku> findDokusByCategory(Category category,int start,int count) {
		Query query = getEntityManager().createNativeQuery("SELECT doku.* FROM doku,CATEGORY_DOKU WHERE doku.DOKU_ID = CATEGORY_DOKU.DOKU_ID AND CATEGORY_DOKU.CATEGORY_ID = :categoryID",Doku.class);
        query.setParameter("categoryID", category.getId());
		if (start != 0){
			query.setFirstResult(start);
		}
		if (count != 0){
			query.setMaxResults(count);
		}
		return (List<Doku>) query.getResultList();
	}

}